package com.cf.controller;


import com.cf.entity.Item;
import com.cf.entity.Result;
import com.cf.entity.SupportOrder;
import com.cf.service.ItemService;
import com.cf.service.SupportOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@CrossOrigin
public class PayController {
    @Autowired
    private SupportOrderService supportOrderService;
    @Autowired
    private ItemService itemService;
    // 应用的APPID
    private final String APP_ID = "2021000118667169";
    // 生成的应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZQgBS00oXxsENerYHVUgz3oT9gJVAf69vwIVFxUP7ZQFjJ32tKw1D5NPKGzoejMczHUJ+DQPTHAcap3PpG7d4wZUwiT2N0DhWG+JWHX3+1VJFnaQPrbMr26KK8xXwmEpwWdR9Ge76kxs/DzZAHGxonzi5xhjO0tr2bDHx8ku6LJ+wW8qL1jrCqosnzOrOrskv4qPX8FeK+I0VgeCGnNoivvVZRjdKdedsYc9wCFuiq9+Ns3Bcht7Vjt1o86EYxaw4z4HSGzWrsyi/uMtRaGGws5G6CTDxkBjBOslJNoYAdS99fM1dXbq/DLl2n6h45B3ds6UxE2CvvoEO6fhKtKjFAgMBAAECggEALWgRonh5VkwLvIujzM5mov+FlXn4PnDWMJzwn3hPqPcHDzKPGLRNrNTqLtIcSRralflQTvpaLLz8GdiNDf6pQDzSj9vJge+0EUcXqv33632Wb4vCJOcI07CyGsrksDDetSTYQOxjEphtFSTTpPEG6YRrERdxGC3+s83gileIOjMxwC8iyuFa5eN6epOudAiE+W7DMNRBGPwCl8mKCW8TS31vyLSHEP5zI8zzsTUQ8zyYUQE4LQq4y7IdkbovKElSCai3HM6vg1Q8IFbYZa+jYi3q73ae4EqmruSW6TNnwsLgRbEY0SEmn072PVzfj1OZcjKbHrLbTtu4BL7ofpna4QKBgQDlqWCbyb6VB6ew3RH29O/L3beYFu3CHVVJoLpmsmKdnA9DWkH6y1mT2uNMg4onzqBWvZqUxnfOzH63P7t7HsSH4nRD9ojGdFIO2+uMvMeVoYeNk1xV7W/A02aEMggD1eXpq6qXXYF3qxeuuSQZmXU4PQ30sqN3pVD9hSMDG61aHQKBgQCq1X0dTUpe0m9J9l/3leL+7hpEaZDX8KYhTFq1Ieh1KJSEz8XkAnjxzaPNqeOTG3801YJAN/oTSVMb1vqQ3m4DiPYKshVnPVeJV7E7Mslqxkj3rHZfmUzNJMcgsP++gjodYDT7LmNnlEyDQPfp5QwwX0P2icamXxIfKOm1XWgIyQKBgQDRC7naVGrbsJodTT06830KroidMdG9bYHigSDqtdk56YGjJxcDt/GTuhxH2zv4PAaKrg90+Kq5XD7Dgome6kSuA50c991L9zlyORBRjMyHEP8YCVh1BqlAdazNC9Vr2Flst0uSeBSO3vexnOiVPLAMPtbjM2/ESoBMI9HY1GqYqQKBgCy6Xtq4LNuszzSXTEMfvGIw5zG4ThMrz+NyAWHhceKS8Gfhmpd7Sj1NMTEc5RfUIDcuG79CqLg5/4ePfuVFR5qnVnwwakgwmGW+TwoH3xKUvfAS+J9JHQGtOnHFxgAUSrD8SoLlf2NUQcAv13km3k0f9ERtiFRxGeaMqLwyq5V5AoGBANrRDpcgjv0L/Cg/wPmRr5xZ1l2hoDRmJ+H98cHRT7DrAptPHyTt90YtFDg4/d2WfQ+qkM8ZmPb9QYMRJwWNicBSS0JZPumQj0QqR6kAp+9W878AeB3fg3UunNHId58G9vO6bsO+m1Xuaspsl6GabAEhLyqgIJEXOvpVHjfay+fv";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp8Vk/+V4n/+vfdVg7Cnex3ne5AWIxYjPlAod1xQCyXZLUHD/ANC0319fCdB/hO0DoFkNoWg6svESVTmUaRJnMHpWYyzo/11t5GiBRGAtCLAx9Pi8z/PcDwwmrD/xH+NeshvDLoiCMMxbit2KUeK3nSEDeyZTprKLXsTPNHqGZfFQ2SPIyhVOut8OyiZnxvShtA9OWxwdqS6AvKC1M9YpJM33kSne7RT4dsrhvI6vyxMcR3k6rhO8oBcZotgt2nv4sYk7OFae35HeA4JGk/hNdvSiy0g+S08AVHzGA39tyQPRl9P8uk8uM764jhgf4lZbbgy7beoWTyvfcktdl7QEIQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/success";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/#/pay_step_3";



    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    @ResponseBody
    public Object returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("==============同步回调==============");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] :
                        valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }


       // 调用SDK验证签名
        int i = supportOrderService.updateStatus(params.get("uuid"));
        if (i==1){
            return new Result(203,"付款成功",null);
        }else {
            return new Result(400,"失败付款",null);
        }



    }

    @RequestMapping("/alipay")
    @ResponseBody
    public Object alipay(HttpServletResponse httpResponse,SupportOrder supportOrder) throws IOException {

        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        Item item = itemService.selectItemByIid(supportOrder.getIid());
        //商户订单号，商户网站订单系统中唯一订单号，必填
        // 测试中数据随机产生，开发中调用项目中的真实数据即可
        //生成随机Id
        String out_trade_no = supportOrder.getOrderuuid();
        //付款金额，必填
        String total_amount =Double.toString(supportOrder.getAllmoney());
        //订单名称，必填
        String subject =item.getIname();
        //商品描述，可空
        String body = item.getIintro();
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
//        httpResponse.setContentType("text/html;charset=" + CHARSET);
//        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
        return new Result(202,"成功",form);
    }
}
